﻿using Bee.Domain;
using Bee.Infrastructure;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Bee.Repository
{
    public class M3U8CrawlerServer : IM3U8CrawlerInterface
    {
        private static Logger logger = new Logger(typeof(M3U8CrawlerServer));

        public List<M3U8Model> CrawlM3U8Models(string url)
        {
            List<M3U8Model> list = new List<M3U8Model>();
            string html = string.Empty;
            try
            {
                html = HttpHelper.DownloadHtml(url);
                if (string.IsNullOrEmpty(html))
                {
                    logger.Warn("未能解析到正确的hml数据");
                    return null;
                }
                HtmlDocument document = new HtmlDocument();
                document.LoadHtml(html);
                HtmlNodeCollection htmlNodes = document.DocumentNode.SelectNodes("//*[@class='well well-sm']/a");
                foreach (HtmlNode node in htmlNodes)
                {
                    M3U8Model model = new M3U8Model();
                    model.URL = "http://www.yezhulu.net" + node.Attributes[0].Value;
                    string videoHtml = HttpHelper.DownloadHtml(model.URL);
                    HtmlDocument videoDocument = new HtmlDocument();
                    videoDocument.LoadHtml(videoHtml);
                    HtmlNodeCollection videoInfos = videoDocument.DocumentNode.SelectNodes("//meta");
                    foreach (HtmlNode info in videoInfos)
                    {
                        model.Description = GetAttributeContent(info.Attributes, "og:description", model.Description);
                        model.CoverImageLink = GetAttributeContent(info.Attributes, "og:image", model.CoverImageLink);
                        model.Duration = GetAttributeContent(info.Attributes, "", model.Duration);
                        model.Site_Name = GetAttributeContent(info.Attributes, "og:site_name", model.Site_Name);
                        model.Type = GetAttributeContent(info.Attributes, "og:type", model.Type);
                        model.Tag = GetAttributeContent(info.Attributes, "video:tag", model.Tag);
                        model.Title = GetAttributeContent(info.Attributes, "og:title", model.Title);
                        model.URL = GetAttributeContent(info.Attributes, " og:url", model.URL);
                    }
                    Regex reg = new Regex(@"video_duration = \""(\d+)\""");
                    model.Duration = reg.Match(videoHtml).Groups[1].Value;
                    var sourceNodes = videoDocument.DocumentNode.SelectNodes("//source");
                    foreach (var m3u8 in sourceNodes)
                    {
                        model.M38U = m3u8.Attributes["src"].Value;
                    }
                    list.Add(model);
                }
                return list;
            }
            catch (Exception e)
            {
                logger.Error("未能解析到正确的", e);
                return null;
            }
        }

        /// <summary>
        /// 验证属性 和 内容
        /// </summary>
        /// <param name="attribute"></param>
        /// <param name="property"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public string GetAttributeContent(HtmlAttributeCollection attribute, string value, string oldValue)
        {
            string result = oldValue;
            if (attribute == null)
                return result;
            if (attribute["property"] == null || attribute["content"] == null)
                return result;
            if (string.IsNullOrEmpty(attribute["property"].Value) || string.IsNullOrEmpty(attribute["content"].Value))
                return result;
            if (attribute["property"].Value.Equals(value.Trim()))
                result = attribute["content"].Value;
            return result;
        }
    }
}
